import { http } from '@/utils/request'
import { useUserAuthStore } from '@/stores/userAuth'

// 认证相关API
export const authAPI = {
  // 用户登录
  async login(data) {
    try {
      const response = await http.post('/auth/login', data)
      
      // 登录成功后更新状态库
      const userAuthStore = useUserAuthStore()
      userAuthStore.login({
        token: response.token,
        userInfo: response.userInfo
      })
      
      // 更新最后登录时间
      userAuthStore.updateLastLoginTime()
      console.log('登录成功:', response)
      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  },
  
  // 用户注册
  async register(data) {
    try {
      // 构建符合数据库字段的注册数据
      const registerData = {
        username: data.username,
        email: data.email,
        phone: data.phone,
        real_name: data.real_name, // 数据库字段名
        password: data.password,
        user_type: data.user_type, // 数据库字段名
        avatar: data.avatar || '',
        description: data.description || '',
        status: data.status || 1,
        // create_time 由数据库自动生成
      }
      
      const response = await http.post('/auth/register', registerData)
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  },
  
  // 用户登出
  async logout() {
    try {
      await http.post('/auth/logout')
      // 登出后清除状态库
      const userAuthStore = useUserAuthStore()
      userAuthStore.logout()
    } catch (error) {
      console.error('登出失败:', error)
      // 即使API调用失败，也要清除本地状态
      const userAuthStore = useUserAuthStore()
      userAuthStore.logout()
    }
  },
  
  // 刷新token
  async refreshToken() {
    try {
      const response = await http.post('/auth/refresh')
      // 更新token
      const userAuthStore = useUserAuthStore()
      userAuthStore.token = response.token
      localStorage.setItem('token', response.token)
      return response
    } catch (error) {
      console.error('刷新token失败:', error)
      throw error
    }
  },
  
  // 获取用户信息
  async getUserInfo() {
    try {
      const response = await http.get('/auth/user-info')
      // 更新用户信息
      const userAuthStore = useUserAuthStore()
      userAuthStore.setUserInfo(response)
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  },
  
  // 更新用户信息
  async updateUserInfo(data) {
    try {
      // 构建符合数据库字段的更新数据
      const updateData = {
        real_name: data.real_name,
        email: data.email,
        phone: data.phone,
        avatar: data.avatar,
        description: data.description,
        // update_time 由数据库自动更新
      }
      
      const response = await http.put('/auth/user-info', updateData)
      // 更新本地用户信息
      const userAuthStore = useUserAuthStore()
      userAuthStore.setUserInfo(response)
      return response
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  },
  
  // 修改密码
  async changePassword(data) {
    try {
      const response = await http.post('/auth/change-password', data)
      return response
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  },
  
  // 忘记密码
  async forgotPassword(data) {
    try {
      const response = await http.post('/auth/forgot-password', data)
      return response
    } catch (error) {
      console.error('忘记密码失败:', error)
      throw error
    }
  },
  
  // 重置密码
  async resetPassword(data) {
    try {
      const response = await http.post('/auth/reset-password', data)
      return response
    } catch (error) {
      console.error('重置密码失败:', error)
      throw error
    }
  },
  
  // 上传头像
  async uploadAvatar(formData) {
    try {
      const response = await http.post('/auth/upload-avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      // 更新本地头像
      const userAuthStore = useUserAuthStore()
      userAuthStore.setAvatar(response.avatar)
      
      return response
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  },
  
  // 检查用户名是否可用
  async checkUsername(username) {
    try {
      const response = await http.get('/auth/check-username', { username })
      return response
    } catch (error) {
      console.error('检查用户名失败:', error)
      throw error
    }
  },
  
  // 检查邮箱是否可用
  async checkEmail(email) {
    try {
      const response = await http.get('/auth/check-email', { email })
      return response
    } catch (error) {
      console.error('检查邮箱失败:', error)
      throw error
    }
  },
  
  // 检查手机号是否可用
  async checkPhone(phone) {
    try {
      const response = await http.get('/auth/check-phone', { phone })
      return response
    } catch (error) {
      console.error('检查手机号失败:', error)
      throw error
    }
  },
  
  // 发送验证码
  async sendVerificationCode(data) {
    try {
      const response = await http.post('/auth/send-code', data)
      return response
    } catch (error) {
      console.error('发送验证码失败:', error)
      throw error
    }
  },
  
  // 验证验证码
  async verifyCode(data) {
    try {
      const response = await http.post('/auth/verify-code', data)
      return response
    } catch (error) {
      console.error('验证验证码失败:', error)
      throw error
    }
  }
} 